import React = require("react");
import { BaseComponent } from "components/common/base-component";
import { ShoppingCartService } from "mobile/services/shoppingCartService";
import ReactDOM = require("react-dom");
import { Panel } from "./panel";
import { ShoppingService } from "mobile/services/shoppingService";
import { ImageService } from "maishu-services-sdk";
import { component } from "components/common/component";



export interface Props {
    product: Product,
}

export interface State {
    hideProperties: boolean,
    productSelectedText: string,
    count: number,
}

@component()
export class ProductInfo extends BaseComponent<Props, State> {

    productPanel: ProductPanel;

    static defaultProps: Props = { product: {} as Product };

    constructor(props) {
        super(props);
        this.state = {
            hideProperties: false,
            count: 1,
            productSelectedText: this.productSelectedText({} as Product)
        };
    }
    private productSelectedText(product: Product) {
        var str = '';
        var props = product.Fields || [];
        for (var i = 0; i < props.length; i++) {
            // var options = props[i].Options;
            // for (var j = 0; j < options.length; j++) {
            //     if (options[j].Selected) {
            //         str = str + options[j].Name + ' ';
            //         break;
            //     }
            // }
            str = str + props[i].value + ' ';
        }
        str = str + (this.state == null ? 1 : this.state.count) + '件';
        return str;
    }
    addToShoppingCart() {
        let product = this.props.product;
        let shoppingCart = this.createService(ShoppingCartService);
        return shoppingCart.setItemCount(product, this.state.count);
    }
    updateProductCount(value) {
        // this.state.count = value;
        // this.state.productSelectedText = this.productSelectedText(this.state.product);
        // this.setState(this.state);
        this.setState({ count: value, productSelectedText: this.productSelectedText(this.props.product) })
    }
    render() {
        let { hideProperties } = this.state;
        let { product } = this.props;
        let selectedText = this.productSelectedText(product);
        return <div className="productInfo-control">
            <ul key={10} className="list-group">
                <li className="list-group-item product-name">
                    {product.Name}
                    {product.Title ?
                        <h5 className="">
                            {product.Title}
                        </h5> : null
                    }
                </li>
                {/* <li className="list-group-item">
                    <span>类别：</span>
                    <span>{product.ProductCategoryName}</span>
                </li> */}
                <li className="list-group-item">
                    <span>价格：</span>
                    <span className="price">{product.Price != null ? '￥' + product.Price.toFixed(2) : ''}</span>
                </li>
                <li className="list-group-item" onClick={() => this.productPanel.show()}>
                    <span>
                        已选：{selectedText}
                    </span>
                    <span className="pull-right">
                        <i className="icon-chevron-right"></i>
                    </span>
                </li>
            </ul>
            <hr key={20} />
            {!hideProperties ?
                <div key={30} className="container">
                    <h4 style={{ fontWeight: 'bold', width: '100%' }}>商品信息</h4>
                    {(product.Arguments || []).map(o => (
                        <div key={o.key} style={{ marginBottom: '10px' }}>
                            <div className="pull-left" style={{ width: '100px' }}>{o.key}</div>
                            <div style={{ marginLeft: '100px' }}>{o.value}</div>
                            <div className="clearfix"></div>
                        </div>
                    ))}
                    <div className="empty-info"
                        style={{ display: (product.Arguments || []).length == 0 ? 'block' : 'none' }}>
                        暂无商品信息
                </div>
                </div> : null}
            {!hideProperties ?
                <hr key={40} /> : null}
            {product == null || product.Id == null ? null :
                ReactDOM.createPortal(
                    <ProductPanel key="productPanel"
                        ref={(o) => this.productPanel = o || this.productPanel}
                        parent={this} product={product} />, this.page.element)}
        </div>
    }
}

class ProductPanel extends React.Component<{ product: Product, parent: ProductInfo } & React.Props<ProductPanel>,
    { product: Product, count: number, customProperties: Array<CustomProperty>, }> {

    panel: Panel;
    imageService: ImageService;

    constructor(props) {
        super(props);
        this.state = {
            product: this.props.product,
            count: this.props.parent.state.count,
            customProperties: []
        };

        this.imageService = this.props.parent.createService(ImageService);
    }
    private decrease() {
        let count = this.state.count;
        if (count == 1) {
            return;
        }

        count = count - 1;
        // this.state.count = count;
        // this.setState(this.state);
        this.setState({ count })

    }
    private increase() {
        let count = this.state.count;
        count = count + 1;
        // this.state.count = count;
        // this.setState(this.state);
        this.setState({ count })
        this.props.parent.updateProductCount(count);
    }
    private onProductsCountInputChanged(event: Event) {
        let value = Number.parseInt((event.target as HTMLInputElement).value);
        if (!value) return;
        // this.state.count = value;
        // this.setState(this.state);
        this.setState({ count: value });
        this.props.parent.updateProductCount(value);
    }
    private onFieldSelected(property: CustomProperty, name: string) {
        property.Options.forEach(o => {
            o.Selected = o.Name == name
        })

        var properties: { [name: string]: string } = {};
        this.state.customProperties.forEach(o => {
            properties[o.Name] = o.Options.filter(c => c.Selected)[0].Value;
        });

        let page = this.props.parent.page;
        let shop = page.createService(ShoppingService);
        return shop.productByProperies(this.state.product.Id, properties)
            .then(o => {

                // this.props.parent.state.product = o;
                // this.props.parent.setState(this.props.parent.state);
                // this.props.parent.setState({ product: o });

                // this.state.product = o;
                // this.setState(this.state);
                this.setState({ product: o });

                // productStore.value = o;
            });
    }
    show() {
        this.panel.show('right');
    }
    async componentDidMount() {
        let page = this.props.parent.page;
        let shopping = page.createService(ShoppingService);
        let p = this.state.product;
        if (p != null && p.Id != null) {
            let customProperties = await shopping.productCustomProperties(p.GroupId, p.Id);
            // this.state.customProperties = customProperties;
            // this.setState(this.state);
            this.setState({ customProperties: customProperties });
        }

    }
    render() {
        let p = this.state.product;
        let customProperties = this.state.customProperties;
        return (
            <Panel ref={(o) => this.panel = o}
                header={
                    <div>
                        <nav>
                            <ul className="nav nav-tabs">
                                <li className="text-left" style={{ width: '30%' }}>
                                    <button onClick={() => this.panel.hide()} style={{ border: 'none', padding: 10, backgroundColor: 'inherit' }}>关闭</button>
                                </li>
                            </ul>
                        </nav>
                        <div style={{ paddingTop: "10px" }}>
                            <div className="pull-left" style={{ width: 80, height: 80, marginLeft: 10 }}>
                                <img src={this.imageService.imageSource(p.ImagePath)} className="img-responsive" />
                            </div>
                            <div style={{ marginLeft: 100, marginRight: 70 }}>
                                <div>{p.Name}</div>
                                <div className="price">￥{p.Price.toFixed(2)}</div>
                            </div>
                        </div>
                        <div className="clearfix"></div>
                    </div>
                }
                body={
                    <div>
                        {customProperties.map(o => (
                            <div key={o.Name} className="container row">
                                <div className="pull-left" style={{ width: 60 }}>
                                    <span>{o.Name}</span>
                                </div>
                                {o.Options.map(c => (
                                    <div key={c.Name} style={{ marginLeft: 60 }}>
                                        <button onClick={() => this.onFieldSelected(o, c.Name)}
                                            className={c.Selected ? 'cust-prop selected' : 'cust-prop'}>
                                            {c.Name}
                                        </button>
                                    </div>
                                ))}
                            </div>
                        ))}
                    </div>
                }
                footer={
                    <div>
                        <div className="form-group">
                            <div style={{ width: 60, textAlign: 'left' }} className="pull-left">
                                <span>数量</span>
                            </div>
                            <div style={{ marginLeft: 60 }}>
                                <div className="input-group">
                                    <span className="input-group-btn">
                                        <button className="btn btn-default" onClick={() => this.decrease()}>
                                            <i className="icon-minus" ></i>
                                        </button>
                                    </span>
                                    <input className="form-control" type="number" value={`${this.state.count}`}
                                        onChange={this.onProductsCountInputChanged.bind(this)} />
                                    <span className="input-group-btn">
                                        <button className="btn btn-default" onClick={() => this.increase()}>
                                            <i className="icon-plus"></i>
                                        </button>
                                    </span>
                                </div>
                            </div>
                        </div>
                        <div className="clearfix"></div>
                        <button onClick={() => { this.props.parent.addToShoppingCart(); this.panel.hide() }} className="btn btn-primary btn-block"
                            data-dialog="toast:'成功添加到购物车'">
                            加入购物车
                    </button>
                    </div>
                } />
        );
    }
}